import {ConfigStore} from '../storage/configStore';
import {createElement, createId} from './utils';
import type {ProxyConfigItem} from '../types/config';

// 检查代理状态
function checkProxyStatus(proxyConfigs: ProxyConfigItem[]) {
    const hasGlobalProxy = proxyConfigs.some(p => p.type === 'global' && p.enabled);
    const hasInterfaceProxy = proxyConfigs.some(p => p.type === 'interface' && p.enabled);
    return {hasGlobalProxy, hasInterfaceProxy};
}

// 更新添加按钮状态
function updateAddButtonState(addBtn: HTMLButtonElement, proxyConfigs: ProxyConfigItem[]) {
    const {hasGlobalProxy, hasInterfaceProxy} = checkProxyStatus(proxyConfigs);
    const disabled = hasGlobalProxy && hasInterfaceProxy;
    addBtn.disabled = disabled;
    addBtn.classList.toggle('disabled', disabled);
}

// 检查url是否合法
function checkUrl(url: string) {
    if (url.indexOf("{target}") === -1) {
        alert("请确保URL中包含{target}占位符");
        return false;
    }
    const pattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/;
    return pattern.test(url);
}

/**
 * 渲染代理配置面板
 */
export function renderProxyConfigs(container: HTMLElement) {
    // 清空容器
    container.innerHTML = '';
    // 获取代理配置列表
    const proxyConfigs = ConfigStore.getConfig().proxyConfigs || [];
    if (proxyConfigs.length === 0) {
        proxyConfigs[0] = {
            id: createId(),
            type: 'global',
            enabled: false,
            url: ''
        };
    }
    const proxyConfig: ProxyConfigItem = proxyConfigs[0];

    // 添加标题和添加按钮
    const addBtn = createElement('button', {
        attrs: {
            class: 'add-proxy-btn',
            style: proxyConfigs.length === 0 ? '' : 'display:none'
        },
        children: [document.createTextNode('添加代理')]
    });

    const header = createElement('div', {
        attrs: {
            class: 'proxy-section'
        },
        children: [
            createElement('div', {
                attrs: {
                    class: 'proxy-header'
                },
                children: [
                    createElement('h4', {
                        children: [document.createTextNode('代理服务配置')]
                    }),
                    addBtn
                ]
            })
        ]
    });

    container.appendChild(header);

    // 渲染每个代理配置项
    proxyConfigs.forEach((config, index) => {
        const proxyItem = createElement('div', {
            attrs: {
                class: 'proxy-item'
            }
        });

        // 代理项头部（包含开关和操作按钮）
        const delBtn = createElement('div', {
            attrs: {
                class: 'proxy-controls'
            },
            children: [
                createElement('button', {
                    attrs: {
                        class: 'delete-btn'
                    },
                    children: [document.createTextNode('删除')]
                })
            ]
        });
        const itemHeader = createElement('div', {
            attrs: {
                class: 'proxy-header'
            },
            children: [
                // 开关
                createElement('label', {
                    attrs: {
                        class: 'switch'
                    },
                    children: [
                        createElement('input', {
                            attrs: {
                                type: 'checkbox',
                                checked: config.enabled ? 'checked' : ''
                            }
                        }),
                        createElement('span', {
                            attrs: {
                                class: 'slider'
                            }
                        })
                    ]
                }),
                // 操作按钮组
                delBtn
            ]
        });

        // 代理类型选择
        const typeSelector = createElement('div', {
            attrs: {
                class: 'radio-group'
            },
            children: [
                createElement('label', {
                    attrs: {
                        class: 'radio-label'
                    },
                    children: [
                        createElement('input', {
                            attrs: {
                                type: 'radio',
                                name: `proxy-type-${index}`,
                                value: 'global',
                                checked: config.type === 'global' ? 'checked' : ''
                            }
                        }),
                        createElement('span', {
                            attrs: {
                                class: 'radio-text'
                            },
                            children: [document.createTextNode('全局代理')]
                        })
                    ]
                }),
                createElement('label', {
                    attrs: {
                        class: 'radio-label'
                    },
                    children: [
                        createElement('input', {
                            attrs: {
                                type: 'radio',
                                name: `proxy-type-${index}`,
                                value: 'interface',
                                checked: config.type === 'interface' ? 'checked' : ''
                            }
                        }),
                        createElement('span', {
                            attrs: {
                                class: 'radio-text'
                            },
                            children: [document.createTextNode('接口代理')]
                        })
                    ]
                })
            ]
        });

        // 代理URL输入框
        const urlInput = createElement('input', {
            attrs: {
                type: 'text',
                class: 'proxy-url',
                value: config.url,
                placeholder: '请输入代理地址，例如：http://localhost:8080/{target}'
            }
        });
        const urlInputDiv = createElement('div', {
            attrs: {
                class: 'proxy-url-container'
            },
            children: [
                urlInput
            ]
        });

        // 组装代理项
        proxyItem.appendChild(itemHeader);
        proxyItem.appendChild(typeSelector);
        proxyItem.appendChild(urlInputDiv);

        // 添加到容器
        container.appendChild(proxyItem);

        // 绑定事件处理

        itemHeader.addEventListener('click', () => {
            const checkbox = itemHeader.querySelector('input[type="checkbox"]') as HTMLInputElement;
            proxyConfig.enabled = checkbox.checked;
            const config = ConfigStore.getConfig();
            config.proxyConfigs = proxyConfigs;
            ConfigStore.saveConfig(config);
        });

        typeSelector.addEventListener('change', () => {
            const querySelector = typeSelector.querySelector('input:checked') as HTMLInputElement;
            const type = querySelector.value;
            if (type === 'global' || type === 'interface') {
                proxyConfig.type = type;
                const config = ConfigStore.getConfig();
                config.proxyConfigs = proxyConfigs;
                ConfigStore.saveConfig(config);
            }
        });

        urlInput.addEventListener('blur', () => {
            const url = urlInput?.value;
            if (url && checkUrl(url) && url !== proxyConfig.url) {
                proxyConfig.url = url;
                const config = ConfigStore.getConfig();
                config.proxyConfigs = proxyConfigs;
                ConfigStore.saveConfig(config);
            }
        });


    });
}